<template>
  <div class="quality_result" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="timeQuery" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="skill">
                  <span class="ski ski1">{{$t('public.agent')}} :</span>
                  <!-- <el-select v-model="timeQuery.user"
                               multiple
                               filterable
                               size="mini"
                               :placeholder="$t('report.pleChoseAgent')">
                      <el-option
                        v-for="item in agentOptions"
                        :label="item.label"
                        :value="item.value"
                        :key="item.value">
                      </el-option>
                    </el-select> -->
                  <m7Select class="el-select" filterable multiple :options="selectAgents" v-model="timeQuery.user"></m7Select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id = "id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                {{$t('report.quaCheckedAll')}}<br/>
                {{$t('report.quaCheckedCallNum')}}<br/>
                {{$t('report.quaCheckedSesNum')}}<br/>
                {{$t('report.quaFine')}}<br/>
                {{$t('report.quaOntest')}}<br/>
                {{$t('report.quaBelowGrade')}}<br/>
                {{$t('report.quaAppealsNum')}}<br/>
                {{$t('report.quaRejectNum')}}<br/>
                <!--{{$t('report.quaParentItem')}}<br/>-->
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <!--<report-table :data="tableData" :config="headOptions"></report-table>-->
        <el-table
          :data="tableData"
          style="width: 100%"
          :height="theight"
          :style="style"
          stripe
          ref="table"
          :show-header="true"
        >
          <el-table-column
            v-for="(item, index) in headOptions"
            v-if="item.name !== 'good' && item.name !== 'qualified' && item.name !== 'noQualified' && item.name !== 'appeal' && item.name !== 'appealReject'"
            :prop="item.name"
            :key="index"
            :label="item.displayname"
            :show-overflow-tooltip="true"
            sortable
            :sort-method="sortMethod(item.name)"
          ></el-table-column>
          <el-table-column
            :key="index"
            v-for="(item, index) in headOptions"
            v-if="item.name === 'good' || item.name === 'qualified' || item.name === 'noQualified' || item.name === 'appeal' || item.name === 'appealReject'"
            :prop="item.name"
            :label="item.displayname"
            :show-overflow-tooltip="true"
          >
            <template scope="scope">
              <p>通话：{{scope.row[item.name + '_call']}}</p>
              <p>在线：{{scope.row[item.name + '_chat']}}</p>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import { deepClone } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, searchTime, colorConfigArr, checkTime } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'

  export default {
    name: 'quality_result',
    data () {
      return {
        style: 'width: 100%;',
        theight: 'fixed',
        isResizeFive: true,
        agentOptions: [],
        isFold: false,
        loading: false,
        id: 'autoqc_agent_result_report',
        title: this.$t('report.qualityReportResult'),
        timeQuery: {
          user: []
        },
        dialogVisible: false,
        serverData: [],
        headOptions: [],
        highchartsDefaultOptions: {
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.qualityReportResult') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        }
        return  this.agentOptions
      },
      tableData () {
        if (!this.serverData || this.serverData.length === 0) {
          return []
        }
        this.$nextTick(function () {
          if (this.$refs.table) {
            this.$refs.table.doLayout()
          }
          this.tableStyle()
          // setTimeout(function () { // 饿了么table第一次渲染是表头和body自适应之前高度是不准的，需要二次触发获取正确的高度
          //   window.onresize()
          // }, 500)
        })
        let data = deepClone(this.serverData)
        for (let j = 0; j < data.length; j++) {
          data[j].good = `通话：${data[j].good_call}   在线：${data[j].good_chat}`
          data[j].qualified = `通话：${data[j].qualified_call}   在线：${data[j].qualified_chat}`
          data[j].noQualified = `通话：${data[j].noQualified_call}   在线：${data[j].noQualified_chat}`
          data[j].appeal = `通话：${data[j].appeal_call}   在线：${data[j].appeal_chat}`
          data[j].appealReject = `通话：${data[j].appealReject_call}   在线：${data[j].appealReject_chat}`
        }
        return data
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let headerConfig = this.headOptions
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'total' || item.name === 'totalCall' || item.name === 'totalChat' || item.name === 'appeal_count' || item.name === 'appeal_reject_count') {
            let serie = { name: item.displayname, data: [], valueName: item.name }
            seriesArray.push(serie)
          }
          if (item.name === 'good' || item.name === 'qualified' || item.name === 'noQualified' || item.name === 'appeal' || item.name === 'appealReject') {
            let serieCall = { name: item.displayname + '(通话)', data: [], valueName: item.name + '_call' }
            seriesArray.push(serieCall)
            let serieChat = { name: item.displayname + '(在线)', data: [], valueName: item.name + '_chat' }
            seriesArray.push(serieChat)
          }
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(datas[i].agentName)
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(parseFloat(datas[i][seriesArray[j].valueName]))
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    methods: {
      tableStyle () { // 动态计算表格的实际高度和屏幕高度来判断是否表头吸顶
        // tableHeight 表格body(内容)实际高度
        // headerHeight 表格header(表头)实际高度
        // footerHeight 表格footer(合计)实际高度
        // toolHeight 顶部工具条高度 + 三级导航高度 + 30px间距
        // winHeight 浏览器窗口高度
        if (this.isResizeFive) {
          let parentDom = this.$el
          if (!parentDom) {
            return
          }
          let parentHeight = parentDom ? parentDom.clientWidth : 0
          let tableDom = parentDom.querySelectorAll('.el-table .el-table__body-wrapper .el-table__body')[0]
          let tableHeight = tableDom ? tableDom.clientHeight + 6 : 0 // 6是滚条的高度
          let tableWidth = tableDom.clientWidth
          let headerDom = parentDom.querySelectorAll('.el-table .el-table__header-wrapper .el-table__header')[0]
          let headerHeight = headerDom ? headerDom.clientHeight : 0
          let footerDom = parentDom.querySelectorAll('.el-table .el-table__footer-wrapper .el-table__footer')[0]
          let footerHeight = footerDom ? footerDom.clientHeight : 0
          let nav1Dom = document.querySelectorAll('.top-nav')[0]
          let nav2Dom = document.querySelectorAll('.right_detail .top_nav')[0]
          let toolHeight = (nav1Dom ? nav1Dom.clientHeight : 0) + (nav2Dom ? nav2Dom.clientHeight : 0) + 30
          let winHeight = document.body.clientHeight
          let hollHeight = tableHeight + headerHeight + footerHeight
          if (winHeight - toolHeight - hollHeight < 0) { // 浏览器H - 工具条H - 三级导航H - tableH < 0 表示剩余空间放不下全部的table
            this.theight = 'fixed' // 饿了么的固定表头API
            this.style = 'width: 100%; height: calc(100vh - ' + toolHeight + 'px);' // 固定表头需要确切的表格高度
          } else {
            this.theight = '' // 不需要表头固定
            this.style = 'width: 100%;'
          }
          if (footerDom) {
            if (parentHeight - tableWidth > 8) { // 里外宽度不一致时footer和body之间会有穿透 6是纵向滚条的宽度
              footerDom.parentNode.style.height = '34px'
              footerDom.parentNode.style.marginTop = '6px'
            } else {
              footerDom.parentNode.style.height = '40px'
              footerDom.parentNode.style.marginTop = '0px'
            }
          }
        }
      },
      isShowFold (bool) {
        this.isFold = bool
      },
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          // account: this.$store.state.session.user.account,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id, accountId: this.$store.state.session.user.account }
        }
        let query = deepClone(this.timeQuery)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryAgentAutoqcResultReport', data).then((res) => {
          // 表头
          this.headOptions = deepClone(res.tableHeader.Config)
          for (var i = 0; i < res.data.length; i++) {
            res.data[i].errorRate += '%'
            let agent = this.$store.getters.agents[res.data[i].agentId]
            res.data[i].agentName = agent ? agent.displayName + '(' + agent.exten + ')' : ''
          }
          this.serverData = deepClone(res.data)
          this.loading = false
        })
      },
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryAgentAutoqcResultReport', data).then((res) => {
          this.loading = false
          var headOptions = deepClone(res.tableHeader.Config)

          var ConfigsTemp = []
          headOptions && headOptions.forEach(config => {
            ConfigsTemp.push(config)
            if (config.name === 'agentName') {
              ConfigsTemp.push({
                show: config.show,
                displayname: '工号',
                name: 'agentExten'
              })
            }
          })

          var headers = headOptionsToXlsxHeaders(ConfigsTemp)

          let data = deepClone(res.data)
          for (let j = 0; j < data.length; j++) {
            data[j].errorRate += '%'
            let agent = this.$store.getters.agents[res.data[j].agentId]
            data[j].agentName = agent ? agent.displayName : ''
            data[j].agentExten = agent ? agent.exten : ''

            data[j].good = `通话：${data[j].good_call}   在线：${data[j].good_chat}`
            data[j].qualified = `通话：${data[j].qualified_call}   在线：${data[j].qualified_chat}`
            data[j].noQualified = `通话：${data[j].noQualified_call}   在线：${data[j].noQualified_chat}`
            data[j].appeal = `通话：${data[j].appeal_call}   在线：${data[j].appeal_chat}`
            data[j].appealReject = `通话：${data[j].appealReject_call}   在线：${data[j].appealReject_chat}`
          }

          var dh = XlsxUtil.getDownloadHelper(headers, deepClone(data))
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.qualityReportResult') + timeStamp)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportAutoqcAgentReportExcel',
          Query: {reportType: this.id, accountId: this.$store.state.session.user.account}
        }
        let query = deepClone(this.timeQuery)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportRobotMessageExcel', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.qualityReportResult') + searchTime(this.timeQuery), id: this.id})
      },
      sortMethod (name) {
        return function (c, d) {
          if (typeof c[name] === 'number') {
            return d[name] - c[name]
          } else if (c[name].indexOf(':') > -1 && d[name].indexOf(':') > -1 && parseInt(c[name].split(':').join('')) && parseInt(d[name].split(':').join('')) && name !== 'ReportTime' && name !== 'reportTime') {
            return parseInt(d[name].split(':').join('')) - parseInt(c[name].split(':').join(''))
          } else {
            if (c[name].indexOf('%') > -1 || (d[name].indexOf('s') > -1 && c[name].indexOf('s') > -1)) {
              return parseFloat(d[name]) - parseFloat(c[name])
            } else {
              return d[name].localeCompare(c[name], 'zh')
            }
          }
        }
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agentOptions = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
        this.search()
      })
    },
    mounted () {
      let self = this
      window.addEventListener('resize', self.tableStyle)
    },
    activated () { // 在别的模块缩放了窗口回来的时候要触发一下重新计算
      if (!this.isResizeFive) {
        let self = this
        window.addEventListener('resize', self.tableStyle)
      }
      this.isResizeFive = true
      this.tableStyle()
    },
    deactivated () { // 离开后在别的模块缩放窗口不触发tableStyle()
      let self = this
      window.removeEventListener('resize', self.tableStyle)
      this.isResizeFive = false
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .quality_result
    padding-bottom 20px
    .m7-select
      width 200px
    .export
      .pdf
        margin 0px
    .search
      .ski1
        margin-right 24px
</style>
